<?php
/*
Plugin Name: Designs
Description: Declares a plugin that will create a custom post type
Version: 1.0
Author: Han Lai
*/
global $design_form_complete;
global $drawblog_post_form_complete;
 $img_path="/opt/lampp/htdocs/wordpress/wp-content/plugins/Design/images";
 $thumbnail_size=120;
 $post_image_location='/Design/postimages/';

add_action('init','create_design');

add_action( 'init', 'create_design_taxonomies', 0 );
//add_action('do_meta_boxes','remove_design_metaboxes');
add_action('admin_init','add_design_canvas');
add_action( 'save_post','save_design_image_to_post',10,2);
//add_action('edit_form_after_title','display_design_meta_box');
//add_action('the_content','display_design_add_to_post');//TODO
//add_action('save_post', 'save_design_image_to_post');//TODO
add_action( 'wp_enqueue_script', 'load_jquery' );
function load_jquery() {
    wp_enqueue_script( 'jquery' );
}

function create_design(){
	register_post_type('design',
		array(
			'labels'=>array(
				'name'=> 'Designs',
				'singular_name'=>'Design',
				'add_new_item'=>'Add New Design',
				'edit'=>'Edit',
				'edit_item'=>'Edit Design',
				'new_item'=>'New Design',
				'view'=>'View',
				'view_item'=>'View Design',
				'search_item'=>'Search Design',
				'not_found'=>'No Designs found',
				'not_found_in_trash'=>'No Designs found in Trash',
				'parent'=> 'Parent Design'
				),
			'public'=>true,
			'menu_position'=>15,
			'supports' =>array( 'title' ),
			'taxonomies'=>array(''),
	 		'menu_icon'=>plugins_url('images/logo.png',__FILE__),
	 		'has_archive'=> true
		)
	);
}



function create_design_taxonomies(){
register_taxonomy(
          'design_type',
          'design', array(
                                        'labels' => array(
                                                                'name' => 'Design category',
                                                                'add_new_item' => 'Add New Design category',
                                                                'new_item_name' => "New Design category"
                                                                  ),
                                       'show_ui' => true,
                                       'show_tagcloud' => true,
                                       'hierarchical' => true
                                               )
	                           );
}


//add_action( 'admin_init', 'my_admin' );

function remove_design_metaboxes(){
	//remove_meta_box('submitdiv','design','side');
	//remove_meta_box('likes_meta','design','advance');

}

function add_design_canvas(){
	add_meta_box('design_meta_box','Design Image Detail','display_design_meta_box','design','normal','high');
}




function display_design_meta_box($post){
	global $design_form_complete;
	global $image_exists;
	// Get image string
	$meta = get_post_meta($post->ID, 'drawblog_image');
	$design_image =$meta[0];
		if (($design_image) && 
		(is_file( WP_CONTENT_DIR . $post_image_location . $design_image)) && 
		(getimagesize(  WP_CONTENT_DIR .$post_image_location . $design_image) !== false)){
			$image_exists = 'true';
		} else {
			$image_exists = 'false';
		}

		// Add post canvas
		wp_enqueue_script( 'my-ajax-request', plugin_dir_url( __FILE__ ) . '/ajax.js', array( 'jquery' ) );
		wp_localize_script( 'my-ajax-request', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ,'postCommentNonce' => wp_create_nonce( 'myajax-post-comment-nonce' )) );
		include "display_design_canvas.php";



}


function save_design_image_to_post($post_id,$post){
	if($post->post_type=='design'){
		if(isset($_POST['vector_images'])){
			$json = serialize ($_POST['vector_images']);
			delete_post_meta($post_id, 'json');
			add_post_meta($post_id, 'json', $json);
		}
		if(isset($_POST['design_img'])){
			$data=$_POST['design_img'];
			$raw_data = str_replace(' ','+',$data);
			$filtered_data=substr($raw_data, strpos($raw_data, ",")+1);
			$data = base64_decode($filtered_data);
			$new_image = uniqid('p'.$post_id.'_').'.png';
			$fp = fopen(WP_CONTENT_DIR . '/Design/images/'.$new_image, 'wb' );
			fwrite( $fp, $data);
			fclose( $fp );
			delete_post_meta($post_id, 'vector_images');
			add_post_meta($post_id, 'vector_images', $new_image);
		}
		
	}

}
/*
* Methods to open an image file and generate an thumbnail img. Used for
* handling uploaded image file. 
*/
function generateThumbnail($sourcef,$thumbf,$newSize){
$file=$sourcef;
$newFile=$thumbf;
$xoffset=0;
$yoffset=0;
	list($width, $height) = getimagesize($file);
	//set dimensions
	if($width>$height){
		$newW=$newSize;
		$newH=floor($height/$width*$newSize);
		$yoffset=floor(($newSize-$newH)/2);
	}else{
		$newH=$newSize;
		$newW=floor($width/$height*$newSize);
		$xoffset=floor(($newSize-$newW)/2);
	}
	$thumb=open_image($file);
	$thumb_p=imagecreatetruecolor($newSize,$newSize);
	imagealphablending($thumb_p,false);
	imagesavealpha($thumb_p,true);
	imagealphablending($thumb,true);
	$bg = imagecolorallocatealpha ( $thumb_p, 255, 255, 255,127 );
	imagefill($thumb_p,0,0,$bg);
	imagecopyresampled($thumb_p,$thumb,$xoffset,$yoffset,0,0,$newW,$newH,$width,$height);
	imagesavealpha($thumb_p,true);
	imagepng($thumb_p,$newFile);
}
function open_image ($file) {
    $size=getimagesize($file);
    switch($size["mime"]){
        case "image/jpeg":
            $im = imagecreatefromjpeg($file); //jpeg file
        break;
        case "image/gif":
            $im = imagecreatefromgif($file); //gif file
      break;
      case "image/png":
          $im = imagecreatefrompng($file); //png file
      break;
    default: 
        $im=false;
    break;
    }
    return $im;
}
/*
* The following sections are for handling ajax query from client web pages. 
*/
/* Return the list of gems for json array to be processed by js.
*/
add_action( 'wp_ajax_list_gems', 'list_gems' );

function list_gems(){
	if (is_user_logged_in()){
	global $wpdb;
	$author=get_the_author_meta("ID");
	$result=$wpdb->get_results("SELECT id_gem,thumb_path,pic_path FROM design_gems where (id_author=0 OR id_author=".$author.") and type=1;");
	$response=json_encode($result);
	header("Content-Type:application/json");
	echo $response;
	}
	exit;	
}

add_action('wp_ajax_list_chains','list_chains');

function list_chains(){
	if(is_user_logged_in()){
	global $wpdb;
	$author=$_POST['authID'];
	$result=$wpdb->get_results("SELECT iddesign_extendable as id, default_length as length,img_path as path FROM design_extendable ;");
	$response=json_encode($result);
	header("Content-Type:application/json");
	echo $response;
	}
	exit;	
}
add_action('wp_ajax_list_compartments','list_compartments');
function list_compartments(){
	global$wpdb;
	$author=get_the_author_meta("ID");
	$result=$wpdb->get_results("SELECT thumb_path,pic_path FROM design_gems where (id_author=0 OR id_author=".$author.") and type=2;");
	$response=json_encode($result);
	header("Content-Type:application/json");
	echo $response;

	exit;	
}
/*
***************************************************************************************
* This is to handle an upload request from first page, where user upload an image of a gem. yy
*/
add_action('wp_ajax_uploadgem','uploadgem');
function uploadgem(){
	global$wpdb;
	global $img_path;
	$filename=$_FILES['fileToUpload']['name'];
	if(isset($filename)&& is_user_logged_in()){
		//hash a name, save the file
		$extention=pathinfo($filename,PATHINFO_EXTENSION);
		$hashname=uniqid();
		$file=$img_path."/".$hashname.".".$extention;
		$thumbpath=$img_path."/thumb/".$hashname.".png";
		$authorid=get_the_author_meta("ID");
		while(file_exists($file)){
			$hashname=uniqid();
			$file=$img_path."/".$hashname.".".$extention;
			$thumbpath=$img_path."/thumb/".$hashname.".png";
		}
		move_uploaded_file($_FILES['fileToUpload']["tmp_name"],$file);
		//Generate thumbnail img
		generateThumbnail($file,$thumbpath,120);
		// Insert into database
			$wpdb->insert( 
			'design_gems', 
			array( 
				'id_author' => $authorid, 
				'thumb_path' => $thumbpath,
				'pic_path'=>$file,
				'type'=>1 
			), 
			array( 
				'%d', 
				'%s',
				'%s',
				'%d' 
			) 
		);
	}
}
/*
*********************************************************************
* This is to handle upload request from second page, where user create components from multiple
* elements, gems, rings, circles...
* Expect a form with a JSON array of graphic elements, each one with id, rotation degree and size. Serialize it and save to database. 
*/
function uploadComponents(){
	global$wpdb;
	
	global $img_path;
$svg=$_POST['svgElements'];
$filename=$_FILES['fileToUpload']['name'];
//$imgElements=json_decode($svg);
// Directly upload this to database. TODO: can filter this json array and change the address of images. 
if(isset($filename)&&is_user_logged_in()){
	//hash a name, save the file
		$extention=pathinfo($filename,PATHINFO_EXTENSION);
		$hashname=uniqid();
		$authorid=get_the_author_meta("ID");
		while(file_exists($file)){
			$hashname=uniqid();
			$file=$img_path."/".$hashname.".".$extention;
			$thumbpath=$img_path."/thumb/".$hashname.".png";
		}
		move_uploaded_file($_FILES['fileToUpload']["tmp_name"],$file);
		//Generate thumbnail img
		generateThumbnail($file,$thumbpath,120);
		// Insert into database
			$wpdb->insert( 
			'design_complexParts', 
			array( 
				'id_author' => $authorid, 
				'thumb_path' => $thumbpath,
				'pic_path'=>$file,
				'type'=>2 ,
				'jsonString'=>$svg
			), 
			array( 
				'%d', 
				'%s',
				'%s',
				'%d',
				'%s'
			) 
		);
}
}

function uploadCompleteDesign(){
		global$wpdb;
	global $img_path;
$svg=$_POST['svgElements'];
$filename=$_FILES['fileToUpload']['name'];
//$imgElements=json_decode($svg);
// Directly upload this to database. TODO: can filter this json array and change the address of images. 
if(isset($filename)&&is_user_logged_in()){
	//hash a name, save the file
		$extention=pathinfo($filename,PATHINFO_EXTENSION);
		$hashname=uniqid();
		$authorid=get_the_author_meta("ID");
		while(file_exists($file)){
			$hashname=uniqid();
			$file=$img_path."/".$hashname.".".$extention;
			$thumbpath=$img_path."/thumb/".$hashname.".png";
		}
		move_uploaded_file($_FILES['fileToUpload']["tmp_name"],$file);
		//Generate thumbnail img
		generateThumbnail($file,$thumbpath,120);
		// Insert into database
			$wpdb->insert( 
			'design_complexParts', 
			array( 
				'id_author' => $authorid, 
				'thumb_path' => $thumbpath,
				'pic_path'=>$file,
				'type'=>2 ,
				'jsonString'=>$svg
			), 
			array( 
				'%d', 
				'%s',
				'%s',
				'%d',
				'%s'
			) 
		);
}
}

?>